<template>
  <div class="assistant-container">
    <!-- 头部 -->
    <div class="assistant-header">
      <div class="header-left">
        <h2 class="header-title">智能助手</h2>
      </div>
      <div class="header-right">
        <el-button 
          icon="More" 
          circle 
          @click="showMenu"
          class="menu-btn"
        />
      </div>
    </div>

    <!-- 聊天消息区域 -->
    <div class="chat-messages" ref="messageContainer">
      <div 
        v-for="message in messages" 
        :key="message.id" 
        :class="['message', message.type]"
      >
        <div class="message-avatar">
          <el-avatar 
            :size="40"
            :src="message.type === 'assistant' ? '/assistant-avatar.png' : user?.avatar"
            :icon="message.type === 'assistant' ? 'ChatDotRound' : 'User'"
          />
        </div>
        <div class="message-content">
          <div class="message-bubble">
            {{ message.content }}
          </div>
          <div class="message-time">
            {{ formatTime(message.timestamp) }}
          </div>
        </div>
      </div>
      <!-- 加载状态 -->
      <div v-if="loading" class="message assistant">
        <div class="message-avatar">
          <el-avatar 
            size="40"
            src="/assistant-avatar.png"
            icon="ChatDotRound"
          />
        </div>
        <div class="message-content">
          <div class="message-bubble loading">
            <span class="loading-dots">
              <span></span>
              <span></span>
              <span></span>
            </span>
          </div>
        </div>
      </div>
    </div>

    <!-- 快捷操作按钮 -->
    <div class="quick-actions" v-if="showQuickActions">
      <div class="quick-action-buttons">
        <el-button 
          v-for="action in quickActions" 
          :key="action.id"
          size="small"
          @click="handleQuickAction(action)"
          class="quick-action-btn"
        >
          {{ action.title }}
        </el-button>
      </div>
    </div>

    <!-- 输入区域 -->
    <div class="input-section">
      <div class="input-container">
        <el-input
          v-model="inputMessage"
          placeholder="请输入问题"
          :disabled="loading"
          @keyup.enter="sendMessage"
          class="message-input"
        >
          <template #append>
            <el-button 
              icon="Microphone" 
              @click="startVoiceInput"
              :disabled="loading"
              class="voice-btn"
            />
          </template>
        </el-input>
        <el-button 
          type="primary"
          icon="Position"
          @click="sendMessage"
          :disabled="!inputMessage.trim() || loading"
          class="send-btn"
        />
      </div>
    </div>

    <!-- 右侧导航栏 -->
    <div class="sidebar-navigation">
      <div class="nav-item" @click="goToNavigation">
        <el-icon size="24"><Location /></el-icon>
        <span>场馆</span>
      </div>
      <div class="nav-item" @click="goToArtists">
        <el-icon size="24"><User /></el-icon>
        <span>艺人</span>
      </div>
      <div class="nav-item" @click="goToVoting">
        <el-icon size="24"><Star /></el-icon>
        <span>投票</span>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick, computed, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { sendMessageStream, getQuickActions } from '@/api/difyAI'
import type { ChatMessage, QuickAction } from '@/types'
import dayjs from '@/utils/dayjs'
import { Location, User, Star } from '@element-plus/icons-vue'
// 响应式数据
const loading = ref(false)
const inputMessage = ref('')
const messages = reactive<ChatMessage[]>([])
const showQuickActions = ref(true)
const menuVisible = ref(false)
const messageContainer = ref<HTMLElement>()

// 快捷操作
const quickActions = ref<QuickAction[]>([
  { id: '1', title: '我想投票', action: 'vote', icon: 'Star' },
  { id: '2', title: '今天天气如何?', action: 'weather', icon: 'Sunny' },
  { id: '3', title: '最火的艺人是哪位', action: 'artist', icon: 'User' },
  { id: '4', title: '演出时间安排', action: 'schedule', icon: 'Calendar' },
  { id: '5', title: '场地设施查询', action: 'facility', icon: 'Location' },
  { id: '6', title: '冷知识分享', action: 'trivia', icon: 'QuestionFilled' }
])

// 获取路由和用户store
const router = useRouter()
const userStore = useUserStore()

// 计算属性
const user = computed(() => userStore.user)

// 返回上一页
const goBack = () => {
  router.back()
}

// 显示菜单
const showMenu = () => {
  menuVisible.value = true
}

// 发送消息 - 流式响应
const sendMessage = async () => {
  if (!inputMessage.value.trim() || loading.value) return
  
  // 检查用户是否已登录
  if (!userStore.isLoggedIn) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  
  const userMessage: ChatMessage = {
    id: Date.now().toString(),
    type: 'user',
    content: inputMessage.value,
    timestamp: new Date().toISOString()
  }
  
  messages.push(userMessage)
  const messageToSend = inputMessage.value
  inputMessage.value = ''
  
  await nextTick()
  scrollToBottom()
  
  loading.value = true
  
  // 创建助手消息占位符
  const assistantMessage: ChatMessage = {
    id: (Date.now() + 1).toString(),
    type: 'assistant',
    content: '',
    timestamp: new Date().toISOString()
  }
  
  messages.push(assistantMessage)
  await nextTick()
  scrollToBottom()
  
        // 使用 Dify AI 流式API
      const cancelStream = sendMessageStream(
        {
          message: messageToSend,
          response_mode: 'streaming'
        },
        (chunk: { type: 'start' | 'chunk' | 'end' | 'error'; message?: string; conversation_id?: string }) => {
          console.log("chunk", chunk);
          // 处理流式响应块
          if (chunk.type === 'start') {
            loading.value = false
            assistantMessage.content = '正在思考...'
            // 强制触发响应式更新
            messages.splice(0, messages.length, ...messages)
            nextTick(() => scrollToBottom())
            loading.value = true
          } else if (chunk.type === 'chunk') {
            loading.value = false
            // 直接追加内容，不使用光标
            assistantMessage.content += chunk.message || ''
            // 强制触发响应式更新
            messages.splice(0, messages.length, ...messages)
            nextTick(() => scrollToBottom())
            loading.value = true
          } else if (chunk.type === 'error') {
            assistantMessage.content = '抱歉，AI服务出现错误，请稍后再试。'
            // 强制触发响应式更新
            messages.splice(0, messages.length, ...messages)
            ElMessage.error(chunk.message || '未知错误')
            nextTick(() => scrollToBottom())
          }
        },
        (fullResponse: string) => {
          loading.value = true
          // 流式响应完成
          assistantMessage.content = fullResponse
          loading.value = false
          // 强制触发响应式更新
          messages.splice(0, messages.length, ...messages)
          nextTick(() => scrollToBottom())
        },
        (error: string) => {
          // 错误处理
          assistantMessage.content = '抱歉，发送消息失败，请重试。'
          loading.value = false
          // 强制触发响应式更新
          messages.splice(0, messages.length, ...messages)
          ElMessage.error(error)
          nextTick(() => scrollToBottom())
        }
      )
  
  // 保存取消函数，以便在需要时取消请求
  // 这里可以根据需要实现取消功能
}

// 处理快捷操作
const handleQuickAction = async (action: QuickAction) => {
  inputMessage.value = action.title
  await sendMessage()
}

// 开始语音输入
const startVoiceInput = () => {
  ElMessage.info('语音输入功能开发中...')
}

// 滚动到底部
const scrollToBottom = () => {
  if (messageContainer.value) {
    messageContainer.value.scrollTop = messageContainer.value.scrollHeight
  }
}

// 格式化时间
const formatTime = (timestamp: string) => {
  return dayjs(timestamp).format('HH:mm')
}

// 清空聊天记录
const clearHistory = () => {
  messages.splice(0, messages.length)
  ElMessage.success('聊天记录已清空')
}

// 获取快捷操作
const fetchQuickActions = async () => {
  try {
    const response = await getQuickActions()
    quickActions.value = response.data
  } catch (error) {
    console.error('获取快捷操作失败:', error)
  }
}

// 导航到场馆页面
const goToNavigation = () => {
  router.push('/navigation')
}

// 导航到艺人页面
const goToArtists = () => {
  router.push('/artists')
}

// 导航到投票页面
const goToVoting = () => {
  router.push('/interaction')
}


// 页面挂载时执行
onMounted(() => {
  // 添加欢迎消息
  messages.push({
    id: 'welcome',
    type: 'assistant',
    content: '您好！我是音乐节智能助手，很高兴为您服务。我可以帮您查询演出信息、艺人详情、场地导航等。请问有什么可以帮您的吗？',
    timestamp: new Date().toISOString()
  })
  
  fetchQuickActions()
})
</script>

<style lang="scss" scoped>
.assistant-container {
  height: 100vh;
  background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
  display: flex;
  flex-direction: column;
  position: relative;
  overflow: hidden;
}

.assistant-header {
  background: rgba(0, 0, 0, 0.8);
  backdrop-filter: blur(10px);
  padding: 15px 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
  z-index: 10;
}

.header-left {
  display: flex;
  align-items: center;
}

.header-title {
  color: white;
  font-size: 18px;
  font-weight: 600;
  margin: 0;
}

.header-right {
  display: flex;
  align-items: center;
}

.menu-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  color: white;
  
  &:hover {
    background: rgba(255, 255, 255, 0.3);
  }
}

.chat-messages {
  flex: 1;
  padding: 20px;
  overflow-y: auto;
  background: linear-gradient(135deg, #1a1a1a 0%, #2d2d2d 100%);
  position: relative;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100"><defs><pattern id="grid" width="10" height="10" patternUnits="userSpaceOnUse"><path d="M 10 0 L 0 0 0 10" fill="none" stroke="rgba(255,255,255,0.05)" stroke-width="0.5"/></pattern></defs><rect width="100" height="100" fill="url(%23grid)"/></svg>');
    opacity: 0.3;
    pointer-events: none;
  }
}

.message {
  display: flex;
  margin-bottom: 20px;
  align-items: flex-start;
  
  &.user {
    flex-direction: row-reverse;
    
    .message-content {
      align-items: flex-end;
    }
    
    .message-bubble {
      background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
      color: white;
      border-radius: 18px 18px 4px 18px;
    }
  }
  
  &.assistant {
    .message-bubble {
      background: rgba(255, 255, 255, 0.1);
      color: white;
      border-radius: 18px 18px 18px 4px;
      backdrop-filter: blur(10px);
    }
  }
}

.message-avatar {
  margin: 0 12px;
  flex-shrink: 0;
}

.message-content {
  display: flex;
  flex-direction: column;
  max-width: 70%;
}

.message-bubble {
  padding: 12px 16px;
  font-size: 14px;
  line-height: 1.4;
  word-wrap: break-word;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  
  &.loading {
    background: rgba(255, 255, 255, 0.1);
    color: white;
  }
}

.loading-dots {
  display: flex;
  gap: 4px;
  
  span {
    width: 6px;
    height: 6px;
    background: white;
    border-radius: 50%;
    animation: loading 1.4s infinite ease-in-out;
    
    &:nth-child(1) { animation-delay: -0.32s; }
    &:nth-child(2) { animation-delay: -0.16s; }
  }
}

@keyframes loading {
  0%, 80%, 100% {
    transform: scale(0);
    opacity: 0.5;
  }
  40% {
    transform: scale(1);
    opacity: 1;
  }
}

.message-time {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.5);
  margin-top: 4px;
  text-align: center;
}

.quick-actions {
  padding: 15px 20px;
  background: rgba(0, 0, 0, 0.3);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.quick-action-buttons {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.quick-action-btn {
  background: rgba(255, 255, 255, 0.9);
  color: #333;
  border: none;
  border-radius: 20px;
  padding: 10px 16px;
  font-size: 14px;
  font-weight: 500;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  text-align: center;
  
  &:hover {
    background: white;
    transform: translateY(-1px);
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}

.input-section {
  padding: 15px 20px;
  background: rgba(0, 0, 0, 0.8);
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.input-container {
  display: flex;
  gap: 10px;
  align-items: center;
}

.message-input {
  flex: 1;
  
  :deep(.el-input__wrapper) {
    background: rgba(255, 255, 255, 0.1);
    border: 1px solid rgba(255, 255, 255, 0.2);
    border-radius: 25px;
    backdrop-filter: blur(10px);
    
    &:hover {
      border-color: rgba(255, 255, 255, 0.3);
    }
    
    &.is-focus {
      border-color: #4CAF50;
      box-shadow: 0 0 0 1px rgba(76, 175, 80, 0.2);
    }
  }
  
  :deep(.el-input__inner) {
    color: white;
    
    &::placeholder {
      color: rgba(255, 255, 255, 0.6);
    }
  }
}

.voice-btn {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  
  &:hover {
    background: linear-gradient(135deg, #764ba2 0%, #667eea 100%);
    transform: scale(1.05);
  }
}

.send-btn {
  background: linear-gradient(135deg, #4CAF50 0%, #45a049 100%);
  color: white;
  border: none;
  border-radius: 50%;
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
  transition: all 0.3s ease;
  
  &:hover {
    background: linear-gradient(135deg, #45a049 0%, #4CAF50 100%);
    transform: scale(1.05);
  }
  
  &:disabled {
    background: rgba(255, 255, 255, 0.2);
    color: rgba(255, 255, 255, 0.5);
    cursor: not-allowed;
    transform: none;
  }
}

.sidebar-navigation {
  position: fixed;
  right: 0;
  top: 0;
  bottom: 0;
  width: 80px;
  background: rgba(0, 0, 0, 0.9);
  backdrop-filter: blur(10px);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100px 0 20px;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.3);
  z-index: 100;
}

.nav-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 15px 0;
  cursor: pointer;
  transition: all 0.3s ease;
  color: rgba(255, 255, 255, 0.7);
  width: 100%;
  
  &:hover {
    background: rgba(255, 255, 255, 0.1);
    color: white;
  }
  
  .el-icon {
    margin-bottom: 5px;
    font-size: 24px;
  }
  
  span {
    font-size: 12px;
    font-weight: 500;
  }
}

// 移动端适配
@media screen and (max-width: 768px) {
  .assistant-header {
    padding: 12px 15px;
  }
  
  .header-title {
    font-size: 16px;
  }
  
  .chat-messages {
    padding: 15px;
  }
  
  .message-content {
    max-width: 85%;
  }
  
  .quick-actions {
    padding: 12px 15px;
  }
  
  .input-section {
    padding: 12px 15px;
  }
  
  .sidebar-navigation {
    width: 60px;
    padding: 80px 0 15px;
  }
  
  .nav-item {
    padding: 10px 0;
    
    .el-icon {
      font-size: 20px;
      margin-bottom: 3px;
    }
    
    span {
      font-size: 10px;
    }
  }
}
</style> 